package ServerStuff;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Properties;
import java.io.InputStream;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import Database.*;
import DataStorageClasses.*;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

	
	private static final long serialVersionUID = 1L;
	
	  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		  
		  HttpSession session = request.getSession();
		  session.setAttribute("loggedIn", false);
		  response.sendRedirect("StartPage.jsp");
		  System.out.println("logged out");
	
	  }

	  
	  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		  	
		  	DatabaseConnector dbConnector = new DatabaseConnector();
		  	Business b = null;
			String name = request.getParameter("username");
			String password = request.getParameter("password");
			String email = "";
			
			request.setAttribute("tryingAgain", false);
			
			try {
				b = dbConnector.signIn(name, password);
				
			} catch (SQLException e) {
				
				e.printStackTrace();
			}
			if(b == null){
				System.out.println("login failed");
				response.sendRedirect("StartPage.jsp");
			}
			if(b != null) {
				email = b.getEmail();
				HttpSession session = request.getSession();
				
				if(session != null) {
					
					session.setAttribute("loggedIn", true);
					session.setAttribute("username", name);
					session.setAttribute("password", password);
					response.sendRedirect("Business.jsp");
					if(email != null)
					{
						if( dbConnector.authenticateReviewer(name, password))
						{
							session.setAttribute("subUser", name);
							session.setAttribute("subPass", password);
							session.setAttribute("subEmail", email);
							session.setAttribute("subloggedIn", true);
						}
					}
				}
			} else {
				request.setAttribute("tryingAgain", true);
				
			
			}
			
		}

	
}
